/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.JavaXML.DOMValidator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import nu.xom.Builder;
import nu.xom.Nodes;
import nux.xom.xquery.XQueryUtil;
import nu.xom.Document;
import nu.xom.Node;

/**
 *
 * @author thanhtq
 */
public class ReadSurvey {

    public static final String SURVEY_XML = "D:\\Project\\thanhtv00011\\Survey\\Survey.xml";

    public Survey readSurvey(String path, String id) {

        List<String> questId = new ArrayList<String>();
        Survey survey = new Survey();
        try {
            Document doc = new Builder().build(new File(path));
            Node node = XQueryUtil.xquery(doc, "//Survey/categorys/category[@id='" + id + "']").get(0);
            survey.setIdSurvey(node.query("@id").get(0).getValue());
            survey.setContentSurvey(node.query("content").get(0).getValue());
            survey.setCommenSurvey(node.query("comment").get(0).getValue());
            Nodes questions = node.query("questionId/id[@enable='1']");
            for (int j = 0; j < questions.size(); j++) {
                questId.add(questions.get(j).query("@id").get(0).getValue());
            }
            survey.setQuestionId(questId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return survey;
    }

    public List<Survey> read() {

        List<Survey> surveys = new ArrayList<Survey>();
        List<String> questId = new ArrayList<String>();
        Survey survey;
        try {
            Document doc = new Builder().build(new File(SURVEY_XML));
            Nodes nodes = XQueryUtil.xquery(doc, "//Survey/categorys/category");
            for (int i = 0; i < nodes.size(); i++) {
                survey = new Survey();
                survey.setIdSurvey(nodes.get(i).query("@id").get(0).getValue());
                survey.setContentSurvey(nodes.get(i).query("content").get(0).getValue());
                survey.setCommenSurvey(nodes.get(i).query("comment").get(0).getValue());
                Nodes questions = nodes.get(i).query("questionId/id[@enable='1']");
                for (int j = 0; j < questions.size(); j++) {
                    questId.add(questions.get(j).query("@id").get(0).getValue());
                }
                survey.setQuestionId(questId);
                surveys.add(survey);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return surveys;
    }
}
